# -*- coding: utf-8 -*-



## ------------------------------------------------------------
## Copyright 2010 Pierre-Antoine Delsart
## 
## This file is part of LeVin.
## 
## LeVin is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
## 
## LeVin is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## 
## You should have received a copy of the GNU General Public License
## along with LeVin.  If not, see <http://www.gnu.org/licenses/>.
## ---------------------------------------------------------------

from PythonQt import QtCore, QtGui
from qtcommon import tr, connect
import wineBase
import datetime



class Ui_Dialog(object):
    """Describes the widget for tasting edition. """
    saDialog = None
    def setupStandAlone(self,parent):
        self.saDialog = QtGui.QDialog(parent)
        self.saDialog.setObjectName("Dialog")
        #self.saDialog.resize(400, 300)
        self.saDialog.setWindowTitle( tr("Add wine tasting") )
        self.saDialog.setModal(True)

        self.verticalLayout = QtGui.QVBoxLayout(self.saDialog)
        self.verticalLayout.setObjectName("verticalLayout")


        connect(self.saDialog, QtCore.SIGNAL('accepted()'), self.accepted)

        self.setupUi(self.saDialog)
        self.verticalLayout.addWidget(self.mainWid)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), self.saDialog.accept)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), self.saDialog.reject)

        #self.saLayout = QtGui.QVBoxLayout(self.saDialog)

    def accepted(self,):
        print 'XXXX'

    def widget(self):
        return self.mainScroll

    def setVisible(self,v):
        self.mainScroll.setVisible(v)
        self.mainWid.setVisible(v)
        if v :
            self.mainScroll.ensureWidgetVisible(self.expertBox)
        
    def setupUi(self, parent):
        self.dateFormat  = wineBase.Tasting.date.date_string
        self.parent = parent
        mainScroll = QtGui.QScrollArea( parent)        

        self.mainScroll = mainScroll
        mainWid = QtGui.QWidget( parent )
        mainScroll.setWidget(mainWid)
        #scrollLayout =  QtGui.QVBoxLayout(self.tastingWid)

        #scrollArea->setBackgroundRole(QPalette::Dark)        
        mainWid.setMinimumWidth(350)
        self.mainWid = mainWid 
        self.formLayout = QtGui.QFormLayout(mainWid)
        self.formLayout.setObjectName("formLayout")        
        #self.formLayout.setSizeConstraint(2) # PythonQt incomp !!
        self.formLayout.setSizeConstraint(QtGui.QLayout.SetMinimumSize) # PythonQt incomp !!
        
        self.wineLabel = QtGui.QLabel( mainWid )
        self.expertBox = QtGui.QCheckBox(mainWid)
        self.expertBox.setText( tr("Expert mode") )
        self.formLayout.setWidget(0, QtGui.QFormLayout.SpanningRole, self.expertBox)
        
        self.label_date = QtGui.QLabel(mainWid)
        self.label_date.setObjectName("label_date")
        self.formLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.label_date)
        self.spinBox_year = QtGui.QDateEdit(mainWid)
        
        ## self.spinBox_year.setMinimum(1900)
        ## self.spinBox_year.setMaximum(200000)
        #currentDate = 
        self.spinBox_year.setDate( QtCore.QDate.currentDate() )
        #self.spinBox_year.setProperty("value", 2010)
        self.spinBox_year.setObjectName("spinBox_year")
        self.formLayout.setWidget(1, QtGui.QFormLayout.FieldRole, self.spinBox_year)
        self.label_rate = QtGui.QLabel(mainWid)
        self.label_rate.setObjectName("label_rate")
        self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.label_rate)
        self.spinBox_rate = QtGui.QSpinBox(mainWid)
        self.spinBox_rate.setMaximum(10)
        self.spinBox_rate.setProperty("value", 5)
        self.spinBox_rate.setObjectName("spinBox_rate")
        self.formLayout.setWidget(2, QtGui.QFormLayout.FieldRole, self.spinBox_rate)

        from tastingText import OrderedTastingAtt
        formWindex = 3
        #for tastAtt,tasteDesc in TastingText.iterattributes():
        self.editWids = []
        for v,attDic in OrderedTastingAtt.iterattributes():
            # a separation label
            labelWg = QtGui.QLabel(mainWid)
            self.formLayout.setWidget(formWindex, QtGui.QFormLayout.SpanningRole, labelWg)
            labelWg.setAlignment(QtCore.Qt.AlignCenter)
            print v ,' at ', formWindex
            formWindex +=1
            setattr(self,'lab_'+v, labelWg )

            # labels+edit widget for each attributes
            for tastAtt,tasteDesc in attDic:
                labelW = QtGui.QLabel(mainWid)
                setattr(self,'lab_'+tastAtt, labelW )
                self.formLayout.setWidget(formWindex, QtGui.QFormLayout.LabelRole, labelW)
                #print tastAtt ,' at ', formWindex
                editW = QtGui.QLineEdit(mainWid)
                self.editWids.append(editW)
                #editW.setVisible(False)
                #labelW.setVisible(False)
                setattr(self,'edit_'+tastAtt, editW )                
                self.formLayout.setWidget(formWindex, QtGui.QFormLayout.FieldRole, editW)
                formWindex+=1

        self.lab_comment = QtGui.QLabel(mainWid)
        self.lab_comment.setObjectName("label_comment")
        self.formLayout.setWidget(formWindex, QtGui.QFormLayout.SpanningRole, self.lab_comment)
        formWindex +=1
        self.edit_comment = QtGui.QPlainTextEdit(mainWid)
        self.edit_comment.setObjectName("plainTextEdit")
        self.formLayout.setWidget(formWindex, QtGui.QFormLayout.FieldRole, self.edit_comment)
        formWindex +=1

        self.editWids.append(self.edit_comment)
                
        self.buttonBox = QtGui.QDialogButtonBox(mainWid)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.formLayout.setWidget(formWindex, QtGui.QFormLayout.SpanningRole, self.buttonBox)

        self.cancelButton = self.buttonBox.button(QtGui.QDialogButtonBox.Cancel)
        self.okButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok)        

        self.retranslateUi(mainWid)

        
        QtCore.QObject.connect(self.expertBox, QtCore.SIGNAL("clicked()"), self.expertMode)
        QtCore.QMetaObject.connectSlotsByName(mainWid)
        self.setWidVisibility(False)

    def retranslateUi(self, mainWid):
        #mainWid.setWindowTitle(QtGui.QApplication.translate("mainWid", "mainWid", None, QtGui.QApplication.UnicodeUTF8))
        self.label_date.setText( tr("Date") )
        self.label_rate.setText( tr("Evaluation") )
        from tastingText import OrderedTastingAtt
        for tastAtt,tasteDesc in OrderedTastingAtt.iterAll():
            labelW=getattr(self,'lab_'+tastAtt )
            labelW.setText( tasteDesc)
            if '_more' in tastAtt :
                # save text in private member, so labels can be switched
                # when expert mode is switched.                
                labelW.referenceS = tasteDesc
        
    def expertMode(self):
        self.setWidVisibility(self.expertBox.isChecked())
        
    def setWidVisibility(self,vis):
        from tastingText import OrderedTastingAtt        
        for v,attDic in OrderedTastingAtt.iterattributes():
            labelG = getattr(self,'lab_'+v)
            labelG.setVisible(vis) # this            
            for tastAtt,tasteDesc in attDic:
                if tastAtt.endswith('_more'):
                    labelW=getattr(self,'lab_'+ tastAtt)
                    if vis :
                        labelW.setText(labelW.referenceS)
                    else:
                        labelW.setText(labelG.text())
                else:
                    getattr(self,'edit_'+tastAtt).setVisible(vis)
                    getattr(self,'lab_'+ tastAtt).setVisible(vis)                

    def update(self, v):
        """ v is a dict mapping the Tasting attributes"""
        d=datetime.datetime.strptime( v['date'], self.dateFormat)
        self.spinBox_year.setDate(QtCore.QDate( d.year, d.month, d.day ) )
        self.spinBox_rate.setValue(v['rate'])
        from tastingText import OrderedTastingAtt        
        for attT, attList in OrderedTastingAtt.iterattributes():
            for att, val in attList:
                t = v[att]
                if t is None : t =''
                getattr(self,'edit_'+att).setText(t)
        self.edit_comment.setPlainText(unicode(v['comment']))        
        

    def updateFromB(self, b, i =None):
        self.wineLabel.setText( '<b>'+b.appellation+', '+b.cru_name+',    '+str(b.millesime)+'</b>' ) 
        if i :
            print 'update tasting '
            pass

    def currentValues(self):
        """Return content of editing widget as a dict """
        from tastingText import OrderedTastingAtt
        d= { 'date' : self.spinBox_year.date().toPyDate().strftime( self.dateFormat),
             'rate' : self.spinBox_rate.value(),
             'comment' :  unicode(self.edit_comment.document().toPlainText() )
             }
        for aType,attList in OrderedTastingAtt.iterattributes():
            for a,v in attList:
                att = 'edit_'+a
                editW=getattr(self,att )
                text = unicode(editW.text())
                if text!='':
                    d[a] = text
        return d

    def clear(self):
        self.spinBox_rate.setValue(5)
        self.spinBox_rate.setValue(2010)

        for ew in self.editWids:            
            ew.clear()
